import type { Directive } from 'vue'

// 创建一个懒加载观察者
const lazyObserver = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target as HTMLImageElement
      img.src = img.dataset.src!
      lazyObserver.unobserve(img)
    }
  })
})
// 创建一个指令, 用于观察懒加载元素
export const lazy: Directive = {
  mounted(el) {
    lazyObserver.observe(el)
  },
  unmounted(el) {
    lazyObserver.unobserve(el)
  },
}
